package com.htzg.premain;



import com.htzg.premain.transformer.MyTransformer;

import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.util.Arrays;
import java.util.Objects;

public class MyAgent {
    public static String handle(String agentArgs, Instrumentation inst) {
        System.out.println("agent参数:" + agentArgs);
        String[] splits = agentArgs.split(",");
        String classNameKeyValue = Arrays.stream(splits).filter(e -> Objects.equals(e.split("=")[0], "handleClassName")).findAny().orElse(null);
        String handleClassName = "";
        if (classNameKeyValue!=null&&!classNameKeyValue.isEmpty()) {
            String[] split = classNameKeyValue.split("=");
            handleClassName = split[1];
        }
        if (handleClassName!=null&&!handleClassName.isEmpty()) {
            inst.addTransformer(new MyTransformer(handleClassName), true);
        }
        Class[] classes = inst.getAllLoadedClasses();
        for (Class cls : classes) {
            System.out.println(cls.getName());
        }
        return handleClassName;
    }

    /**
     * jvm 参数形式启动，运行此方法
     *
     * @param agentArgs
     * @param inst
     */
    public static void premain(String agentArgs, Instrumentation inst) {
        handle(agentArgs, inst);
    }


}

